package org.xxpay.pay.channel;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.xxpay.core.common.constant.MchConstant;
import org.xxpay.core.common.constant.PayConstant;
import org.xxpay.core.common.constant.RetEnum;
import org.xxpay.core.common.domain.api.msg.QueryRetMsg;
import org.xxpay.core.common.exception.ServiceException;
import org.xxpay.core.common.util.MyLog;
import org.xxpay.core.entity.AgentpayPassageAccount;
import org.xxpay.core.entity.TransOrder;
import org.xxpay.core.service.IXxPayAgentpayService;
import org.xxpay.pay.mq.BaseNotify4MchTrans;

/**
 * @author: dingzhiwei
 * @date: 18/08/16
 * @description:
 */
@Component
public abstract class BaseTransNotify extends BaseService implements TransNotifyInterface {

    private static final MyLog logger = MyLog.getLog(BaseTransNotify.class);

    @Autowired
    public BaseNotify4MchTrans baseNotify4MchTrans;


    @Autowired
    public IXxPayAgentpayService xxPayAgentpayService;

    public abstract String getChannelName();

    /**
     * 获取三方支付配置信息
     * 如果是平台账户,则使用平台对应的配置,否则使用商户自己配置的渠道
     * @param transOrder
     * @return
     */
    public String getTransParam(TransOrder transOrder) {
        String payParam = "";
        AgentpayPassageAccount agentpayPassageAccount = commonService.agentpayPassageAccountService.findById(transOrder.getPassageAccountId());
        if(agentpayPassageAccount != null) {
            payParam = agentpayPassageAccount.getParam();
        }
        if(StringUtils.isBlank(payParam)) {
            throw new ServiceException(RetEnum.RET_MGR_PAY_PASSAGE_ACCOUNT_NOT_EXIST);
        }
        return payParam;
    }

    /** 上游明确成功, 更新为成功状态 **/
    protected boolean updateConfirmSuccess(TransOrder dbTransOrder, String chanelOrderNo){

        if(dbTransOrder == null) return false; //系统无此订单 , 更新失败
        if (dbTransOrder.getStatus() != PayConstant.TRANS_STATUS_TRANING) {
            return true;  //订单状态不是处理中,  与更新成功走同一逻辑
        }

        QueryRetMsg retMsg = QueryRetMsg.confirmSuccess(chanelOrderNo);
        return xxPayAgentpayService.processOrderState(dbTransOrder, retMsg);

    }

    /** 上游明确失败, 更新为失败状态 **/
    protected boolean updateConfirmFail(TransOrder dbTransOrder, String channelOrderNo, String channelErrCode, String channelErrMsg){

        if(dbTransOrder == null) return false; //系统无此订单 , 更新失败
        if (dbTransOrder.getStatus() != PayConstant.TRANS_STATUS_TRANING) {
            return true;  //订单状态不是处理中,  与更新成功走同一逻辑
        }

        QueryRetMsg retMsg = QueryRetMsg.confirmFail(channelOrderNo, channelErrCode, channelErrMsg);
        return xxPayAgentpayService.processOrderState(dbTransOrder, retMsg);
    }

}
